package com.sloth.bear.config;

import com.sloth.bear.service.FileIndexService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 定时任务配置
 */
@Slf4j
@Configuration
@EnableScheduling
@EnableAsync
@RequiredArgsConstructor
public class ScheduleConfig {

    private final FileIndexService fileIndexService;
    private final FileManagerProperties properties;

    /**
     * 定时扫描所有目录
     * 启动后5分钟首次执行，之后每小时执行一次
     */
    @Scheduled(
        initialDelayString = "#{${file-manager.scan.initial-delay:300} * 1000}",  // 默认5分钟后首次执行
        fixedDelayString = "#{${file-manager.scan.scan-interval:3600} * 1000}"     // 之后每小时执行一次
    )
    public void scheduledScan() {
        // 检查是否启用定时扫描
        if (!properties.getScan().getEnableScheduledScan()) {
            log.debug("定时扫描已禁用，跳过本次扫描");
            return;
        }

        log.info("开始定时扫描任务");
        try {
            fileIndexService.scanAllDirectories();
            log.info("定时扫描任务完成");
        } catch (Exception e) {
            log.error("定时扫描任务执行失败", e);
        }
    }

    /**
     * 启动时执行一次全量扫描（已禁用，可手动触发）
     */
    // @Scheduled(initialDelay = 30000, fixedDelay = Long.MAX_VALUE)
    public void initialScan() {
        log.info("执行启动扫描任务");
        try {
            fileIndexService.scanAllDirectories();
            log.info("启动扫描任务完成");
        } catch (Exception e) {
            log.error("启动扫描任务执行失败", e);
        }
    }
}